<template>
    <div>
        <div>
            <h1>商品列表</h1>
        </div>
        <div>
            <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
            >
                <el-form-item label="关键字">
                    <el-input
                        v-model="searchForm.keyWord"
                        placeholder="请输入商品名称/ID/关键词"
                        clearable
                    />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="loadProdList"
                        >查询</el-button
                    >
                    <el-button type="primary" @click="onAddProd"
                        >添加商品</el-button
                    >
                    <el-button type="danger" @click="onDeleteBatchProd"
                        >批量删除</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table
                :data="prodList"
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="prodId" label="ID" width="60" />
                <el-table-column prop="prodSpu" label="SPU" width="100" />
                <el-table-column prop="kindName" label="种类" width="80" />
                <el-table-column prop="typeName" label="分类" width="80" />
                <el-table-column prop="prodName" label="名称" width="120" />
                <el-table-column prop="brandName" label="品牌" width="100" />
                <el-table-column prop="unitName" label="单位" width="100" />
                <el-table-column prop="tagName" label="标签" width="100" />
                <el-table-column prop="prodStatus" label="状态" width="100">
                    <template #default="scope">
                        <span v-if="scope.row.prodStatus == 0">草稿</span>
                        <span v-if="scope.row.prodStatus == 1">待审核</span>
                        <span v-if="scope.row.prodStatus == 2">已上线</span>
                        <span v-if="scope.row.prodStatus == 3">已下线</span>
                        <span v-if="scope.row.prodStatus == 4">缺货</span>
                    </template>
                </el-table-column>
                <el-table-column prop="appr" label="供应商" width="160" />
                <el-table-column prop="prodImage" label="封面" width="120">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.prodImage != null"
                            style="width: 100px; height: 100px"
                            :src="scope.row.prodImage"
                            fit="fill"
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    label="创建时间"
                    width="160"
                />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" size="small">商品</el-button>
                        <el-button
                            type="success"
                            size="small"
                            @click="onAddAtta(scope.row)"
                            >商品附件</el-button
                        >
                        <el-button
                            type="danger"
                            size="small"
                            @click="onDelete(scope.row)"
                            >删除</el-button
                        >
                        <el-button
                            type="success"
                            size="small"
                            @click="onBuyProd(scope.row)"
                            >购买</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 20px">
            <el-pagination
                v-model:current-page="searchForm.pageNum"
                v-model:page-size="searchForm.pageSize"
                :page-sizes="[2, 4, 6, 8, 10]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" title="添加商品" width="500">
                <el-form :model="form" ref="ruleFormRef" :rules="rules">
                    <el-form-item
                        label="商品类型"
                        :label-width="formLabelWidth"
                        prop="prodKind"
                    >
                        <el-radio-group v-model="form.prodKind">
                            <el-radio
                                v-for="item in kindList"
                                :value="item.dictValue"
                                :key="item.dictId"
                                >{{ item.dictName }}</el-radio
                            >
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item
                        label="商品分类"
                        :label-width="formLabelWidth"
                        prop="prodType"
                    >
                        <el-tree-select
                            v-model="form.prodType"
                            :data="typeList"
                            :render-after-expand="false"
                            style="width: 240px"
                        />
                    </el-form-item>
                    <el-form-item
                        label="商品名称"
                        :label-width="formLabelWidth"
                        prop="prodName"
                    >
                        <el-input v-model="form.prodName" />
                    </el-form-item>
                    <el-form-item
                        label="商品SPU"
                        :label-width="formLabelWidth"
                        prop="prodSpu"
                    >
                        <el-input v-model="form.prodSpu" />
                    </el-form-item>
                    <el-form-item
                        label="商品品牌"
                        :label-width="formLabelWidth"
                        prop="brandId"
                    >
                        <el-select
                            v-model="form.brandId"
                            placeholder="请选择商品的品牌"
                        >
                            <el-option
                                v-for="item in brandList"
                                :label="item.brandName"
                                :value="item.brandId"
                                :key="item.brandId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品单位"
                        :label-width="formLabelWidth"
                        prop="unitId"
                    >
                        <el-select
                            v-model="form.unitId"
                            placeholder="请选择商品的单位"
                        >
                            <el-option
                                v-for="item in unitList"
                                :label="item.dictName"
                                :value="item.dictId"
                                :key="item.dictId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品标签"
                        :label-width="formLabelWidth"
                        prop="tagId"
                    >
                        <el-select
                            v-model="form.tagId"
                            placeholder="请选择商品的标签"
                        >
                            <el-option
                                v-for="item in tagList"
                                :label="item.dictName"
                                :value="item.dictValue"
                                :key="item.dictId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品供应商"
                        :label-width="formLabelWidth"
                        prop="appr"
                    >
                        <el-input v-model="form.appr" />
                    </el-form-item>
                    <el-form-item
                        label="商品缩略图"
                        :label-width="formLabelWidth"
                        prop="imageUrl"
                    >
                        <el-upload
                            class="avatar-uploader"
                            action="http://127.0.0.1:10010/shop/type/uploadTypeImage"
                            :headers="headers"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                        >
                            <img
                                v-if="imageUrl"
                                :src="imageUrl"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon"
                                ><Plus
                            /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button
                            type="primary"
                            @click="submitForm(ruleFormRef)"
                        >
                            添加
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <div>
            <el-dialog
                v-model="attaFormVisible"
                title="添加商品附件"
                width="500"
            >
                <el-form :model="formAtta">
                    <el-form-item
                        label="商品轮播图"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            v-model:file-list="fileList"
                            action="http://127.0.0.1:10010/shop/type/uploadTypeImage"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :headers="headers"
                        >
                            <el-icon><Plus /></el-icon>
                        </el-upload>

                        <el-dialog v-model="dialogVisible">
                            <img
                                w-full
                                :src="dialogImageUrl"
                                alt="Preview Image"
                            />
                        </el-dialog>
                    </el-form-item>
                    <el-form-item
                        label="商品视频"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            v-model:file-list="videoList"
                            class="upload-demo"
                            action="http://127.0.0.1:10010/shop/type/uploadTypeImage"
                            multiple
                            :on-preview="handlePreview"
                            :on-remove="handleVideoRemove"
                            :before-remove="beforeRemove"
                            :before-upload="beforeVideoUpload"
                            :limit="1"
                            :on-exceed="handleExceed"
                            :headers="headers"
                        >
                            <el-button type="primary">上传视频</el-button>
                            <template #tip>
                                <div class="el-upload__tip">
                                    作用于商品详情页顶部轮插的视频介绍，最大限制20MB.
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item
                        label="上架时间"
                        :label-width="formLabelWidth"
                    >
                        <el-radio-group v-model="formAtta.upFlag">
                            <el-radio :value="0">立即上架</el-radio>
                            <el-radio :value="1">定时上架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item
                        label=""
                        :label-width="formLabelWidth"
                        v-if="formAtta.upFlag == 1"
                    >
                        <el-date-picker
                            v-model="formAtta.upTime"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="请选择定时上架时间"
                        />
                    </el-form-item>
                    <el-form-item
                        label="定时下架"
                        :label-width="formLabelWidth"
                    >
                        <el-switch
                            v-model="formAtta.downFlag"
                            :active-value="1"
                            :inactive-value="0"
                        />
                    </el-form-item>
                    <el-form-item
                        label=""
                        :label-width="formLabelWidth"
                        v-if="formAtta.downFlag == 1"
                    >
                        <el-date-picker
                            v-model="formAtta.downTime"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="请选择定时下架时间"
                        />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="attaFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button type="primary" @click="onsubmitAddProdAtta">
                            提交
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import {
    getProdList,
    getDictList,
    getSelectTypeTree,
    getBrandList,
    addProd,
    addProdAtta,
    deleteBatchProd,
    deleteProd,
} from "@/api/api.ts";
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";

const prodList = ref([]);
const searchForm = ref({
    pageNum: 1,
    pageSize: 2,
    keyWord: null,
});
const total = ref(0);

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
    prodKind: null,
    prodType: null,
    prodName: null,
    appr: null,
    unitId: null,
    tagId: null,
    prodSpu: null,
    prodImage: null,
    brandId: null,
});
const kindList = ref([]);
const typeList = ref([]);
const brandList = ref([]);
const unitList = ref([]);
const tagList = ref([]);

const imageUrl = ref("");
const headers = ref({
    token: sessionStorage.getItem("token"),
});
const ruleFormRef = ref<FormInstance>();

const checkImageUrl = (rule: any, value: any, callback: any) => {
    if (imageUrl.value == null || imageUrl.value == "") {
        return callback(new Error("请上传图片"));
    }

    // 校验通过
    callback();
};

const rules = ref({
    prodKind: [
        { required: true, message: "请选择商品的类型", trigger: "change" },
    ],
    prodType: [
        { required: true, message: "请选择商品分类", trigger: "change" },
    ],
    prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
    prodSpu: [{ required: true, message: "请输入商品SPU", trigger: "blur" }],
    brandId: [{ required: true, message: "请选择商品品牌", trigger: "change" }],
    unitId: [
        { required: true, message: "请选择商品的单位", trigger: "change" },
    ],
    tagId: [{ required: true, message: "请选择商品标签", trigger: "change" }],
    appr: [{ required: true, message: "请输入商品供应商", trigger: "blur" }],
    imageUrl: [{ validator: checkImageUrl, trigger: "blur" }],
});

const attaFormVisible = ref(false);
const formAtta = ref({
    prodId: null,
    upFlag: null,
    upTime: null,
    downFlag: null,
    downTime: null,
    attaImages: null,
    attaVideo: null,
});
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const videoList = ref<UploadUserFile[]>([]);
const multipleSelection = ref<any[]>([]);

const beforeVideoUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (rawFile.type !== "video/mp4") {
        ElMessage.error("请上传MP4格式的视频!");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("视频文件不能超过 2MB!");
        return false;
    }
    return true;
};

// 购买
const onBuyProd = (row: any) => {
    console.log("onBuyProd", row);
};

// 删除商品
const onDelete = (row: any) => {
    ElMessageBox.confirm("删除数据后无法恢复,您确认要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "放弃",
        type: "warning",
    })
        .then(() => {
            // 确认删除
            console.log("确认删除");
            deleteProd(row.prodId).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success("删除成功");
                    loadProdList();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        })
        .catch(() => {
            // 取消删除
            console.log("取消删除");
        });
};

// 批量删除商品
const onDeleteBatchProd = () => {
    console.log("onDeleteBatchProd");
    let ids = [];
    // 参数检查
    if (multipleSelection.value.length == 0) {
        ElMessage.error("请选择要删除的商品");
        return;
    }
    multipleSelection.value.forEach((item) => {
        ids.push(item.prodId);
    });
    console.log("ids", ids);

    ElMessageBox.confirm("删除数据后无法恢复,您确认要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "放弃",
        type: "warning",
    })
        .then(() => {
            // 确认删除
            console.log("确认删除");
            deleteBatchProd(ids).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success("删除成功");
                    loadProdList();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        })
        .catch(() => {
            // 取消删除
            console.log("取消删除");
        });
};

// 多选后的商品列表
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
    console.log("handleSelectionChange", multipleSelection.value);
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
};

const handleVideoRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
    console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
    console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
    ElMessage.warning(
        `The limit is 3, you selected ${
            files.length
        } files this time, add up to ${
            files.length + uploadFiles.length
        } totally`
    );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `Cancel the transfer of ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    );
};

// 显示添加产品附件对话框
const onAddAtta = (row: any) => {
    // 清空轮播图
    fileList.value = [];

    // 清空视频
    videoList.value = [];

    formAtta.value = {
        prodId: null,
        upFlag: null,
        upTime: null,
        downFlag: null,
        downTime: null,
        attaImages: null,
        attaVideo: null,
    };
    formAtta.value.prodId = row.prodId;
    attaFormVisible.value = true;

    console.log("onAddAtta", row);
};

// 提交添加产品附件
const onsubmitAddProdAtta = () => {
    // 获取轮播图地址
    let attaImagesList: any = [];
    fileList.value.forEach((item) => {
        console.log("item", item, item.response.data);
        attaImagesList.push(item.response.data);
    });
    formAtta.value.attaImages = JSON.stringify(attaImagesList);

    // 获取视频地址
    if (videoList.value.length <= 0) {
        ElMessage.error("请上传视频");
        return;
    }
    formAtta.value.attaVideo = videoList.value[0].response.data;

    console.log("formAtta.value", formAtta.value);

    addProdAtta(formAtta.value).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("添加成功");
            attaFormVisible.value = false;
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 表单校验后提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 表单校验通过了
            submitAddProd();
        } else {
            // 表单校验没通过
            console.log("error submit!", fields);
        }
    });
};

const submitAddProd = () => {
    form.value.prodImage = imageUrl.value;
    addProd(form.value).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("添加成功");
            dialogFormVisible.value = false;
            loadProdList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    //imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    imageUrl.value = response.data;
};

// 显示添加商品对话框
const onAddProd = () => {
    form.value = {
        prodKind: null,
        prodType: null,
        prodName: null,
        appr: null,
        unitId: null,
        tagId: null,
        prodSpu: null,
        brandId: null,
        prodImage: null,
    };
    imageUrl.value = "";
    dialogFormVisible.value = true;
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    searchForm.value.pageSize = val;
    loadProdList();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    searchForm.value.pageNum = val;
    loadProdList();
};

// 获取商品列表
const loadProdList = () => {
    getProdList(searchForm.value).then((res) => {
        if (res.data.code == 200) {
            total.value = res.data.data.total;
            prodList.value = res.data.data.records;
        }
    });
};

// 页面加载钩子函数
onMounted(() => {
    loadProdList();

    // 获取商品类型列表
    getDictList(1).then((res) => {
        if (res.data.code == 200) {
            kindList.value = res.data.data;
        }
    });
    // 获取商品分类多级选择框数据
    getSelectTypeTree().then((res) => {
        if (res.data.code == 200) {
            typeList.value = res.data.data;
        }
    });
    // 获取品牌列表
    getBrandList({
        pageNum: 1,
        pageSize: 999999,
    }).then((res) => {
        if (res.data.code == 200) {
            brandList.value = res.data.data.records;
        }
    });
    // 获取商品单位
    getDictList(2).then((res) => {
        if (res.data.code == 200) {
            unitList.value = res.data.data;
        }
    });
    // 获取商品标签
    getDictList(3).then((res) => {
        if (res.data.code == 200) {
            tagList.value = res.data.data;
        }
    });
});
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
